import 'dart:io';
import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';

class ChatHistoryDetailPage extends StatelessWidget {
  final String conversationId;
  const ChatHistoryDetailPage({super.key, required this.conversationId});

  @override
  Widget build(BuildContext context) {
    final Box box = Hive.box('app');
    final String key = 'aiChatMessages_' + conversationId;
    final List<dynamic>? msgs = box.get(key) as List<dynamic>?;
    final List<_Msg> data = _parse(msgs);

    return Scaffold(
      appBar: AppBar(title: Text('会话 $conversationId')),
      body:
          data.isEmpty
              ? const Center(child: Text('暂无消息'))
              : ListView.builder(
                padding: const EdgeInsets.all(12),
                itemCount: data.length,
                itemBuilder: (context, index) {
                  final m = data[index];
                  return Align(
                    alignment:
                        m.isUser ? Alignment.centerRight : Alignment.centerLeft,
                    child: Container(
                      margin: const EdgeInsets.only(bottom: 10),
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color:
                            m.isUser
                                ? Theme.of(context).colorScheme.primary
                                : Theme.of(
                                  context,
                                ).colorScheme.surfaceContainerHighest,
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          if (m.imagePath != null)
                            ClipRRect(
                              borderRadius: BorderRadius.circular(8),
                              child: Image.file(
                                File(m.imagePath!),
                                width: 160,
                                height: 160,
                                fit: BoxFit.cover,
                              ),
                            ),
                          if (m.imagePath != null) const SizedBox(height: 6),
                          Text(
                            m.text,
                            style: TextStyle(
                              color:
                                  m.isUser
                                      ? Colors.white
                                      : Theme.of(context).colorScheme.onSurface,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            _formatTime(m.ts),
                            style: TextStyle(
                              fontSize: 12,
                              color:
                                  m.isUser
                                      ? Colors.white70
                                      : Theme.of(
                                        context,
                                      ).colorScheme.onSurface.withOpacity(0.6),
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
    );
  }

  List<_Msg> _parse(List<dynamic>? msgs) {
    final List<_Msg> res = [];
    if (msgs == null) return res;
    for (final item in msgs) {
      if (item is Map) {
        final String text = (item['text'] ?? '').toString();
        final bool isUser = (item['isUser'] ?? false) == true;
        final int ts = int.tryParse((item['ts'] ?? '0').toString()) ?? 0;
        final String? imagePath = item['imagePath']?.toString();
        res.add(_Msg(text: text, isUser: isUser, ts: ts, imagePath: imagePath));
      }
    }
    return res;
  }

  String _formatTime(int ts) {
    if (ts <= 0) return '--:--';
    final dt = DateTime.fromMillisecondsSinceEpoch(ts);
    return '${dt.hour.toString().padLeft(2, '0')}:${dt.minute.toString().padLeft(2, '0')}';
  }
}

class _Msg {
  final String text;
  final bool isUser;
  final int ts;
  final String? imagePath;
  _Msg({
    required this.text,
    required this.isUser,
    required this.ts,
    this.imagePath,
  });
}
